//
//  TKLoginController.m
//  Ticket
//
//  Created by 小禹宝宝 on 2017/10/10.
//  Copyright © 2017年 cy55. All rights reserved.
//

#import "TKLoginController.h"


#import "NSString+JCKit.h"

@interface TKLoginController ()
<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (assign, nonatomic) BOOL needStop;

@end
@implementation TKLoginController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.loginBtn.backgroundColor = [BLColorConfig mainColor];
    self.loginBtn.layer.cornerRadius = 15;
    self.loginBtn.layer.masksToBounds = true;
    [self ks_setupLeftBackBarButtonItemWithColor:nil];
//    [self ks_setupRightButtonItemWithTitle:@"注册" image:nil highLightedImage:nil];
    self.navigationItem.title = @"登录";
    
    self.verificationCodeTextField.tintColor = [BLColorConfig mainColor];
    self.verificationCodeTextField.textColor = [BLColorConfig textColor];
    self.phoneNumberTextField.tintColor = [BLColorConfig mainColor];
    self.phoneNumberTextField.textColor = [BLColorConfig textColor];
}

- (void)ks_leftBackButtonPressed:(UIButton  *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)ks_rightButtonPressed:(id)sender {
    //注册界面
}

#pragma mark -Action

- (IBAction)loginAciton:(id)sender {
    //登录
    if ([self.phoneNumberTextField.text isEqualToString:@""]) {
        [self ks_showToast:@"手机号码不能为空"];
        return;
    }
    if ([self.verificationCodeTextField.text isEqualToString:@""]) {
        [self ks_showToast:@"验证码不能为空"];
        return;
    }
    if (![self.phoneNumberTextField.text jc_isPhoneNumber]) {
        [self ks_showToast:@"请输入合法手机号码!"];
        return;
    }
    
    
    NSDictionary *params = @{@"mobile":self.phoneNumberTextField.text,@"check_code":self.verificationCodeTextField.text};
    
    [TKAccountManager loginWithParams:params anddecodeClass:[TKAccountInfo class] completion:^(NSInteger error,NSString *msg) {
        if (error == 0) {
            //dissmiss
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self ks_showToast:msg];
        }
    }];

}
- (IBAction)getCodeAction:(id)sender {
    if ([self.phoneNumberTextField.text isEqualToString:@""]) {
        [self ks_showToast:@"手机号码不能为空"];
        return;
    }
    if (![self.phoneNumberTextField.text jc_isPhoneNumber]) {
        [self ks_showToast:@"请输入合法手机号码!"];
        return;
    }
    
    [self reciveSecurityCode];
    [self SecurityCodecountDown];
}

- (void)reciveSecurityCode {
    NSDictionary *params = @{@"mobile":self.phoneNumberTextField.text};
    @weakify(self)
    [BLApi POST:URL_Register_sendCode parameters:params decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
        @strongify(self)
        NSLog(@"%@",responseDataOriginal);
        BLBaseResponse *response = (BLBaseResponse *)responseObject;
        if ([response isSuccess]) {
            
        } else {
            [self ks_showToast:response.errmsg];

        }
        
        if (error) {
            [self ks_showToast:error.domain];
            
        }
    }];
    
}

-(void)SecurityCodecountDown {
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0||_needStop){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                //                [_getCodeBtn setBackgroundColor:[UIColor jc_colorWithHexString:@"2962ff"]];
                //                [_getCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
                _getCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
//                NSLog(@"____%@",strTime);
                [_getCodeBtn setTitle:[NSString stringWithFormat:@"倒计时(%@)",strTime] forState:UIControlStateNormal];
                //                [_getCodeBtn setBackgroundColor:ButtonColorWithGray];
                //                [_getCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
                _getCodeBtn.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField  == self.phoneNumberTextField) {
        [self.verificationCodeTextField becomeFirstResponder];
    }
    if (textField ==self.verificationCodeTextField) {
        [self.verificationCodeTextField resignFirstResponder];
    }
    return YES;
}
@end
